package de.unikoblenz.west.csxpoi.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import de.unikoblenz.west.csxpoi.server.connector.ConnectorFactory;
import de.unikoblenz.west.csxpoi.server.connector.SourceConnector;


/**
 * Request object to forward rest requests to a given set of datastores 
 * who accept rest requests and return the results as a list of POIs
 * 
 * @author Yassin Nachite
 *
 */
public class RestRequest extends Request {

	public RestRequest(ServletContext context) {
		super(context);
		connectors = initConnectors();
	}

	public RestRequest(File sources) {
		super(sources);
		connectors = initConnectors();
	}
	
	/**
	 * Create connectors for each rest datastore in the sources list
	 * @return List of Connector objects
	 */
	@Override
	ArrayList<SourceConnector> initConnectors() {
		ArrayList<SourceConnector> connectorList = new ArrayList<SourceConnector>();
		
		for (String entry : sources) {
			try {
				String[] values = entry.split(",");
				
				if (values[0].equalsIgnoreCase("rest")) {
					if (values[1].equalsIgnoreCase("http")){
						connectorList.add(
								ConnectorFactory.getConnection(
										HTTP, 
										REST, 
										values[2], 
										values[3]));
						}
					else if (values[1].equalsIgnoreCase("sesame")){
						connectorList.add(ConnectorFactory.getConnection(SESAME, REST,	values[2], values[3]));
						}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return connectorList;
	}


	
	@Override
	public List<String> getBases(String[] args) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<String> getContributions(String[] args) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * Gets POIs from every datastore
	 * @return List of POIs
	 */
	@Override
	public List<PoiWrapper> getPois(String[] args) {
		ArrayList<PoiWrapper> resultList = new ArrayList();
		for (int i = 0; i < connectors.size(); i++) {
			resultList.addAll(connectors.get(i).poiRequest(args));
		}
		return resultList;
	}

	@Override
	public List<String> getUsers(String[] args) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<String> getVocabulary(String[] args) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CategoryWrapper> getCategory(String[] args) {
		// TODO Auto-generated method stub
		return null;
	}
}
